<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="permissionQuery">
        <el-form-item>
          <el-input v-model="permissionQuery.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getPermissions">查询</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column prop="name" label="权限名称" width="200" sortable>
      </el-table-column>
      <el-table-column prop="descs" label="权限介绍" width="200" sortable>
      </el-table-column>
      <el-table-column prop="url" label="路径" width="150" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="唯一标识" width="300" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="父权限名称" width="150" sortable>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="permissionQuery.currentPage"
          :page-sizes="[3, 5, 10, 20]"
          :page-size="permissionQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑/新增界面-->
    <el-dialog title="编辑/新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="editForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门介绍" prop="intro">
          <el-input v-model="saveForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门经理" prop="manager.username">
          <el-select v-model="saveForm.manager" clearable value-key="id" placeholder="请选择">
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" prop="parent.name">
          <el-cascader v-model="saveForm.parent"
                       :options="permissionTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-input v-model="saveForm.state" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    return {
      // 分页信息
      pageInfo: {
        total: 0,
        list: []
      },
      // 高级查询
      permissionQuery: {
        keyword: null,
        currentPage: 1,
        pageSize: 10
      },

      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false,//编辑界面是否显示
      editLoading: false, // 编辑页面是否提交中
      saveFormRules: { // 表单验证规则
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        name: '',
        intro: '',
        manager: {
          id: null,
          username: ''
        },
        parent: {
          id: null,
          name: ''
        },
        path: '',
        state: ''
      },
      employees:[],
      // 上级部门
      permissionTree:[]
    }
  },
  methods: {
    // 获取上级部门列表
    getPermissionTree(){
      this.$http.get("/permission/tree")
          .then(result => {
            this.permissionTree = result.data.data;
          })
          .catch(error => {
            this.$message({
              message: error.data.msg,
              type: 'error'
            });
          })
    },
    // 获取经理列表
    getEmployees(){
      this.$http.get("/employee")
          .then(result => {
            this.employees = result.data.data;
          })
          .catch(error => {
            this.$message({
              message: error.data.msg,
              type: 'error'
            });
          })
    },
    // 分页事件
    handleCurrentChange(val) {
      this.permissionQuery.currentPage = val;
      this.getPermissions();
    },
    handleSizeChange(val) {
      this.permissionQuery.pageSize = val;
      this.getPermissions();
    },
    //获取部门列表
    getPermissions() {
      this.$http.post("/permission", this.permissionQuery)
          .then(result => {
            this.pageInfo = result.data.data;
          })
          .catch(error => {
            this.$message({
              message: error.data.msg,
              type: 'error'
            });
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.delete("/permission/" + row.id)
            .then(res => {
              res = res.data
              if (res.success) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.listLoading = false;
                this.permissionQuery.currentPage = 1;
                this.getPermissions();
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
            })
            .catch(res => {
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      if (row.manager == null) {
        this.saveForm.manager = {
          id: null,
          username: ''
        }
      }
      if (row.parent == null) {
        this.saveForm.parent = {
          id: null,
          name: ''
        }
      }else{
        // 利用path属性，回显级联的上级部门
        let parent = row.path.split("/");
        parent.shift();
        parent.pop();
        parent = parent.map(item=>Number.parseInt(item))
        this.saveForm.parent = parent;
      }
      this.getEmployees();//获取经理列表
      this.getPermissionTree();//获取上级部门列表
      // this.$refs['editForm'].resetFields('name');
    },
    //显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        name: '',
        intro: '',
        manager: {
          id: null,
          username: ''
        },
        parent: {
          id: null,
          name: ''
        },
        path: '',
        state: ''
      };
      this.getEmployees();//获取经理列表
      this.getPermissionTree();//获取上级部门列表
      // this.$refs['editForm'].resetFields();
    },
    //编辑&新增
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            if (this.saveForm.parent.length>=0){
              if (this.saveForm.length == 0){
                this.saveForm.parent = {
                  id:null
                }
              }else {
                this.saveForm.parent = {
                  id: this.saveForm.parent[this.saveForm.parent.length - 1]
                }
              }
            }
            this.$http.put("/permission", this.saveForm)
                .then(res => {
                  res = res.data;
                  if (res.success) {
                    this.$message({
                      message: '提交成功',
                      type: 'success'
                    });
                    this.saveFormVisible = false;
                    this.editLoading = false;
                    this.permissionQuery.currentPage = 1;
                    this.getPermissions();
                  } else {
                    this.$message({
                      message: '提交失败',
                      type: 'error'
                    });
                  }
                })
                .catch(res => {
                  this.$message({
                    message: res.data.msg,
                    type: 'error'
                  });
                });
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);

      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/permission",ids)
           .then(res => {
              res = res.data;
              if (res.success) {
                this.listLoading = false;
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.permissionQuery.currentPage = 1;
                this.getPermissions();
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
            })
           .catch(res => {
             this.$message({
               message: res.data.msg,
               type: 'error'
             });
            });
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getPermissions();
  }
}

</script>

<style scoped>

</style>